/*
 *  Texture.cpp
 *  ToolSDL
 *
 *  Created by Seb on 10/01/06.
 *  Copyright 2006 __MyCompanyName__. All rights reserved.
 *
 */
// // Usage exemple:
// GLuint objectID;
// objetID = glGenLists (1);
// glNewList (objetID, GL_COMPILE);
// glEnable (GL_TEXTURE_2D);
// glBindTexture (GL_TEXTURE_2D, texture.getID());
// glBegin (GL_QUADS);
// glTexCoord2f (0.0, 0.0); glNormal3f (1.0, 1.0, 0.0); glVertex3f (1.0, 1.0, -2.0);
// ...
// glEnd ();
// glDisable (GL_TEXTURE_2D);
// glEndList ();

#include "Texture.h"
#include "Image.h"
#include <gl/gl.h>
#include <gl/glu.h>

const int Texture::INVALID_ID = ~1;
GLuint Texture::nextID = 0;

Texture::Texture(const std::string& strFilePath)
: textureID(INVALID_ID), image(new Image(strFilePath))
{
	image->loadBMP();
	bind();
}

const bool Texture::operator==(const Texture& rhs) const
{
	return (image == rhs.image) && (getID() == rhs.getID());
}

void Texture::bind()
{
    textureID = nextID++;
     
	glGenTextures (1, &textureID);
	glBindTexture (GL_TEXTURE_2D, textureID);

	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	//image->convertPixelFormat();
	const int w = image->getWidth();
	const int h = image->getHeight();
	
	//	if w and h are powers of 2, just create the texture
	if (((w & (w-1)) == 0) && ((h & (h-1)) == 0))
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, image->getPixels());
	else
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, w, h, GL_RGB, GL_UNSIGNED_BYTE, image->getPixels());

	//	we don't need the image anymore
	image->freeImage();
}
